from django.shortcuts import render,HttpResponse,redirect
from django.http import JsonResponse
from utils.tencent.sms import send_sms_single
from django.conf import settings
from web import models
from web.forms.project import ProjectModelForm 
from django.db.models import Count
import datetime
import collections

def statistics(request,project_id):
    return render(request,'web/statistics.html')


def priority_chart(request, project_id):
    ret = {
        'status': True,
        'data': None
    } 

    priority_dict = {}
    priorities = models.Issues.priority_choices
    for pri,display in priorities:
        priority_dict[pri] = {'name': display, 'y':0}

    start_date = request.GET.get('start')
    end_date = request.GET.get('end')

    # start_date = datetime.datetime.strptime(start, "%Y-%m-%d").date()
    # end_date = datetime.datetime.strptime(end, "%Y-%m-%d").date()
    
    # result = models.Issues.objects.filter(project_id=project_id).values('priority').annotate(ct=Count('id'))
    result = models.Issues.objects.filter(project_id=project_id,
            create_datetime__range=[start_date,end_date]).\
            values('priority').annotate(ct=Count('id'))
    for item in result:
        priority_dict[item['priority']]['y'] = item['ct']
    ret['data'] = list(priority_dict.values())
    return JsonResponse(ret)


def statistics_projectuser(request, project_id):
    """ 项目成员每个人被分配的任务数量（问题类型的配比）"""
    ret = {
        'status': True,
        'data': {
            'categories':[],
            'series':[
                # {
                #     'name':'',  # 新建/处理中/已关闭...
                #     'data':[]
                # }
            ]
        }
    } 
    start_date = request.GET.get('start')
    end_date = request.GET.get('end')
    
    assigners = models.Issues.objects.filter(project_id=project_id, 
              create_datetime__range=[start_date,end_date]).values('assign','assign__username').annotate(ct=Count('id'))
    # <QuerySet [{'assign': None, 'assign__username': None, 'ct': 1}, {'assign': 2, 'assign__username': 'wq', 'ct': 10}, {'assign': 4, 'assign__username': 'sz', 'ct': 2}]>
    
    # 初始化name; 将data赋值为0，0的个数为assigner人数
    status_choices_dict = dict(models.Issues.status_choices)
    status_idx_in_series = {}
    i = 0
    for idx, text in status_choices_dict.items():
        ret['data']['series'].append({'name': text,'data':[0]*len(assigners)})
        status_idx_in_series[idx] = i
        i+=1
    
    # 第0个assigner
    assigner_idx = 0
    for item in assigners:
        # 处理item['assign__username']是None的情况
        category = item['assign__username'] if item['assign__username'] else '未指派'
        ret['data']['categories'].append(category)
        status_result = models.Issues.objects.filter(assign_id = item['assign'],
                project_id=project_id, create_datetime__range=[start_date,end_date]).values('status').annotate(ct=Count('id'))
        # <QuerySet [{'status': 1, 'ct': 8}, {'status': 2, 'ct': 1}, {'status': 4, 'ct': 1}]>    
        for status_item in status_result:
            # Depend on the idx of status: must start from 1 (1,xx),(2,xx); if (2,xx),(5,xx) will fail
            # ret['data']['series'][status_item['status']-1]['data'][assigner_idx] = status_item['ct']
            
            # add a dict status_idx_in_series, to record the status idx at series. no dependency on idx of status (2,xx)
            ret['data']['series'][status_idx_in_series[status_item['status']]]['data'][assigner_idx] = status_item['ct']
        assigner_idx += 1

    return JsonResponse(ret)


def statistics_projectuser_archive(request, project_id):
    """ 项目成员每个人被分配的任务数量（问题类型的配比）"""
    start = request.GET.get('start')
    end = request.GET.get('end')

    """
    info = {
        1:{
            name:"武沛齐",
            status:{
                1:0,
                2:1,
                3:0,
                4:0,
                5:0,
                6:0,
                7:0,
            }
        },
        2:{
            name:"王洋",
            status:{
                1:0,
                2:0,
                3:1,
                4:0,
                5:0,
                6:0,
                7:0,
            }
        }
    }
    """
    # 1. 所有项目成员 及 未指派
    all_user_dict = collections.OrderedDict()
    all_user_dict[request.tracer.project.creator.id] = {
        'name': request.tracer.project.creator.username,
        'status': {item[0]: 0 for item in models.Issues.status_choices}
    }
    all_user_dict[None] = {
        'name': '未指派',
        'status': {item[0]: 0 for item in models.Issues.status_choices}
    }
    user_list = models.ProjectUser.objects.filter(project_id=project_id)
    for item in user_list:
        all_user_dict[item.user_id] = {
            'name': item.user.username,
            'status': {item[0]: 0 for item in models.Issues.status_choices}
        }

    # 2. 去数据库获取相关的所有问题
    issues = models.Issues.objects.filter(project_id=project_id, create_datetime__gte=start, create_datetime__lt=end)
    for item in issues:
        if not item.assign:
            all_user_dict[None]['status'][item.status] += 1
        else:
            all_user_dict[item.assign_id]['status'][item.status] += 1

    # 3.获取所有的成员
    categories = [data['name'] for data in all_user_dict.values()]

    # 4.构造字典
    """
    data_result_dict = {
        1:{name:新建,data:[1，2，3，4]},
        2:{name:处理中,data:[3，4，5]},
        3:{name:已解决,data:[]},
        4:{name:已忽略,data:[]},
        5:{name:待反馈,data:[]},
        6:{name:已关闭,data:[]},
        7:{name:重新打开,data:[]},
    }
    """
    data_result_dict = collections.OrderedDict()
    for item in models.Issues.status_choices:
        data_result_dict[item[0]] = {'name': item[1], "data": []}

    for key, text in models.Issues.status_choices:
        # key=1,text='新建'
        for row in all_user_dict.values():
            count = row['status'][key]
            data_result_dict[key]['data'].append(count)

    context = {
        'status': True,
        'data': {
            'categories': categories,
            'series': list(data_result_dict.values())
        }
    }

    return JsonResponse(context)